﻿using Task = Sub.TaskPlanningDesk.Model.Objects.Task;
using System.Linq;
using Sub.TaskPlanningDesk.Model.Infrastructure;

namespace Sub.TaskPlanningDesk.Model.Repositories
{
	public class TaskRepository: ITaskRepository
	{
		TaskPlanningDBEntities Context;

		public TaskRepository()
		{
			Context = new TaskPlanningDBEntities("TaskPlanningDBEntities");
		}

		public Task[] GetTasksByProjectID(int projectID)
		{
			return Context.Tasks.Where(r => r.ProjectID == projectID)
				.OrderBy(r => r.Order)
				.Select(r => new Task()
				{
					ID = r.ID,
					Order = r.Order,
					Overview = r.Overview,
					Description = r.Description,
					ProjectID = r.ProjectID,
					Created = r.Created,
					Completed = r.Completed,
					IsDone = r.IsDone,
					TimeSpend = r.TimeSpend
				}).ToArray();
		}

		public Task[] GetChildTasks(int taskID)
		{
			return new Task[] {
				new Task(){ ID = 1, HasChild = true, Overview = "Change sp", Description = "Change sp", Order = 1, ProjectID = 1},
				new Task(){ ID = 2, HasChild = false, Overview = "Localize code", Description = "Localize code", Order = 2, ProjectID = 1},
				new Task(){ ID = 3, HasChild = true, Overview = "Fix bug with image", Description = "Fix bug with image", Order = 3, ProjectID = 1}
			};
		}

		public void Create(Task task)
		{
			Infrastructure.Task dbTask
				= new Infrastructure.Task();
			
			dbTask.Description = task.Description;
			dbTask.Overview = task.Overview;
			dbTask.ProjectID = task.ProjectID;
			dbTask.Created = task.Created;

			int order = 1;
			var orders = Context.Tasks.Where(r => r.ProjectID == task.ProjectID).Select(r => r.Order);
			if (orders.Count() > 0)
				order = orders.Max() + 1;

			dbTask.Order = order;
			Context.Tasks.AddObject(dbTask);
			Context.SaveChanges();
		}

		public void Update(Task task)
		{
			var dbTask = Context.Tasks.Single(r => r.ID == task.ID);
			dbTask.Overview = task.Overview;
			dbTask.Description = task.Description;
			dbTask.Order = task.Order;
			dbTask.Created = task.Created;
			dbTask.IsDone = task.IsDone;
			dbTask.TimeSpend = task.TimeSpend;
			Context.SaveChanges();
		}

		public void Delete(int taskID)
		{
			var task = Context.Tasks.Single(r => r.ID == taskID);
			Context.Tasks.DeleteObject(task);
			Context.SaveChanges();

			var tasks = Context.Tasks.OrderBy(r => r.Order).ToArray();
			int orderStartIndex = 1;
			foreach (var item in tasks)
			{
				item.Order = orderStartIndex++;
			}

			Context.SaveChanges();
		}

		public Task ByID(int taskID)
		{
			var task = Context.Tasks.Single(r => r.ID == taskID);
			return new Task()
			{
				ID = taskID,
				Description = task.Description,
				Order = task.Order,
				Overview = task.Overview,
				ProjectID = task.ProjectID,
				Created = task.Created,
				Completed = task.Completed,
				IsDone = task.IsDone,
				TimeSpend = task.TimeSpend
			};
		}
	}
}
